(function (window, angular, undefined) {'use strict';
    angular.module('reportControllers',[])
    .factory('byDateResource', ['$resource', function($resource){
        return $resource('/index.php/:productType/:baseType',{},{
            post: {
                method:'POST',
                headers:{'Content-Type':'application/x-www-form-urlencoded'},
                transformRequest:function(obj){
                    var str = []
                    for(var key in obj){
                        str.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
                    }
                    return str.join('&')
                },
                isArray: true
            }
        });
    }])
    .factory('indexShowSumResource', ['$resource', function($resource){
        return $resource('/index.php/user/indexShowSum',{},{})
    }])
    .factory('byCompanyResource', ['$resource', function($resource){
        return $resource('/index.php/:product/:top',{},{
            post: {
                method:'POST',
                headers:{'Content-Type':'application/x-www-form-urlencoded'},
                transformRequest:function(obj){
                    var str = []
                    for(var key in obj){
                        str.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
                    }
                    return str.join('&')
                },
                isArray: true
            }
        });
    }])
    .factory('usersTerritoryResource', ['$resource', function($resource){
        return $resource('/index.php/user/regionalInfo',{},{
            get: {
                method:'get',
                transformRequest:function(obj){
                    var str = []
                    for(var key in obj){
                        str.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
                    }
                    return str.join('&')
                },
                isArray: true
            }
        });
    }])
    .factory('usersTerminalResource', ['$resource', function($resource){
        return $resource('/index.php/User/terminalInfo',{},{
            get: {
                method:'get',
                transformRequest:function(obj){
                    var str = []
                    for(var key in obj){
                        str.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
                    }
                    return str.join('&')
                },
                isArray: true
            }
        });
    }])
    .factory('dailyRemainResource', ['$resource', function($resource){
        return $resource('/index.php/:product/getDailyRemain',{},{
            post: {
                method:'POST',
                headers:{'Content-Type':'application/x-www-form-urlencoded'},
                transformRequest:function(obj){
                    var str = []
                    for(var key in obj){
                        str.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
                    }
                    return str.join('&')
                },
                isArray: true
            }
        });
    }])
    .controller('overviewCtrl', ['$scope', '$rootScope', '$routeParams', 'indexShowSumResource', function($scope, $rootScope, $routeParams, indexShowSumResource){
        $(document).ready(function () {
            $('#header').css('min-width', 920)
        });
        $rootScope.currentPage = 'main'
        $scope.functionType = 'report'
        $scope.activeDimension = 'byDate'
        var vm = $scope.vm = {}
        vm.items = [
            {text: '注册企业家数: ', glass: 'data_company', numGlass:'red', dataKey: 'all_enterprize'},
            {text: '安装终端台数: ', glass: 'data_install', numGlass:'green', dataKey: 'all_device'},
            {text: '日活跃: ', glass: 'data_day_active', numGlass:'yellow', dataKey: 'active_day'},
            {text: '月度活跃: ', glass: 'data_month_active', numGlass:'cyan', dataKey: 'active_mon'}
//          {text: '周活: ', bg: 'week', dataKey: 'active_week'},
        ]
        var yesterday = new Date(new Date() - 86400000)
        vm.now = yesterday.getFullYear() + '年' + (yesterday.getMonth() + 1) +  '月' + yesterday.getDate() + '日'
        vm.datas = indexShowSumResource.get({t: +new Date()})
    }])
    .controller('basicActiveCtrl', ['$scope', '$rootScope', '$routeParams', function($scope, $rootScope, $routeParams){
        $rootScope.currentPage = 'basicActive'
        $rootScope.currentProduct = $routeParams.product
    }])
    .controller('basicTrendCtrl', ['$scope', '$rootScope', '$routeParams', function($scope, $rootScope, $routeParams){
        $rootScope.currentPage = 'basicTrend'
        $rootScope.currentProduct = $routeParams.product
    }])
    .controller('retentionCtrl', ['$scope', '$rootScope', 'dailyRemainResource', '$routeParams', function($scope, $rootScope, dailyRemainResource, $routeParams){
        $rootScope.currentPage = 'retention'
        $rootScope.currentProduct = $routeParams.product
        
        var vm = $scope.vm = {}
        vm.tableHead = [
            {name: '日期', key: 'dat', glass: 'item2'},
            {name: '安装数', key: 'ins', glass: 'item1'}
        ]
        var d = [2,3,4,5,6,7,15,30]
        $.each(d, function(index, value){
            vm.tableHead.push({name: '第' + value + '天', key: 'd' + value, glass: 'item1'})
        })
        
        vm.totalSize = 0
        vm.curPage = 0
        vm.perPage = 30
        
        $scope.float2percent = function(floatNum, fix){
            return (floatNum * 100).toFixed(fix) + '%'
        }
        $scope.getDatas = function(){
            var converter = this.converter
            var data = dailyRemainResource.post({product: converter('pageType', this.currentProduct)}, {
                start: $scope.intervalCalendar.begin.dateStr, end: $scope.intervalCalendar.end.dateStr
            })
            data.$promise.then(function(n){
                if(!n.length)
                    return false;
                var regexp = / \d{2}:\d{2}:\d{2}$/
                // 计算最大值最小值
                $.each(n, function(i, row){
                    $.each(d, function(i, num){
                        row['d' + num] = {
                            value: row['d' + num]
                        }
                    })
                })
                $.each(d, function(i, num){
                    var key = 'd' + num
                    var max, min, maxIndex, minIndex
                    max = min = n[0][key].value || 0
                    maxIndex = minIndex = 0
                    $.each(n, function(index, row){
                        if(row[key].value === null){
//                          row[key].value = ' '
                            return;
                        }
                        if(row[key].value > max){
                            max = row[key].value
                            maxIndex = index
                        } else if(row[key].value < min){
                            min = row[key].value
                            minIndex = index
                        }
                    })
                    if(n[maxIndex][key].value !== null){
                        n[maxIndex][key].isMax = true
                        n[minIndex][key].isMin = true
                    }
                })
            })
            return data
        }
        
        function watchFn(newValue, oldValue){
            if(newValue === oldValue){
                return false;
            } else {
                reload()                
            }
        }
        function reload(){
            vm.data = $scope.getDatas('month')
        }
        $scope.$watch('currentProduct', watchFn)
        $scope.$watch('intervalCalendar', watchFn, true)
        vm.data = $scope.getDatas()
    }])
    .controller('companyRankCtrl', ['$scope', '$rootScope', 'byCompanyResource', '$routeParams', function($scope, $rootScope, byCompanyResource, $routeParams){
        $rootScope.currentPage = 'companyRank'
        $rootScope.currentProduct = $routeParams.product
        
        var vm = $scope.vm = {}
        vm.tableHead = {
            duLiBan: [
                {name: '企业名称', key: 'name', glass:'item3'},
                {name: '注册时间', key: 'register_date', glass:'item2'},
                {name: '近期活跃', key: 'count', glass:'item2'},
            ],
            yunShaDu: [
                {name: 'cid', key: 'cid', glass:'item4'},
                {name: '注册时间', key: 'register_date', glass:'item2'},
                {name: '最近登录时间', key: 'last_login', glass:'item2'},
                {name: '近期活跃', key: 'count', glass:'item2'},
            ]
        }
        vm.tableHead['heZuoBan'] = vm.tableHead['yunBeiFen'] =  vm.tableHead['duLiBan']
        vm.totalSize = 0
        vm.curPage = 0
        vm.perPage = 20
        
        $scope.getDatas = function(baseType){
            var converter = this.converter
            var top
            var UpperCase = baseType.replace(/^(\w)/,function(v){return v.toUpperCase()})
            if(this.currentProduct === 'heZuoBan'){
                top = 'top1000' + UpperCase
            } else {
                top = 'top100' + UpperCase
            }
            var data = byCompanyResource.post({product: converter('pageType', this.currentProduct), top: top}, {})
            data.$promise.then(function(n){
                var regexp = / \d{2}:\d{2}:\d{2}$/
                $.each(n, function(i, value){
                    $.each(['date', 'last_login', 'register_date'], function(i, key){
                        if(value[key])
                            value[key] = value[key].replace(regexp, '')
                    })
                })
            })
            return data
        }
        vm.data = $scope.getDatas('month')
    }])
    .controller('usersTerritoryCtrl', ['$scope', '$rootScope', function($scope, $rootScope){
        $rootScope.currentPage = 'usersTerritory'
    }])
    .controller('usersTerminalCtrl', ['$scope', '$rootScope', function($scope, $rootScope){
        $rootScope.currentPage = 'usersTerminal'
    }])
    .directive('basicActive', ['byDateResource', function(byDateResource){
        return {
            restrict: 'A',
            link: function(scope, elem ,attrs){
                $(document).ready(function () {
                    var width = $(".warp").width() - 41
                    $(".warp").width(width)
                    $(".warp_content").width(width);
                    $('#header').css('min-width', width)
                });
                function watchFn(newValue, oldValue){
                    if(newValue === oldValue)
                        return false;
                    if(!chart){
                        chart = createChart()
                    } else {
                        reload()
                    }
                }
                scope.currentBase = 'date'
                var chart = createChart()
                
                scope.$watch('currentProduct', watchFn)
                scope.$watch('intervalCalendar', watchFn, true)
//              scope.$watch('currentBase', watchFn)
                
                function date2str(dateObj){
                    var y = dateObj.getFullYear(),
                        m = dateObj.getMonth() + 1,
                        d = dateObj.getDate()
                    if(m<10) 
                        m = '0' + m
                    if(d<10)
                        d = '0' + d
                    return y+'-'+m+'-'+d
                }
                scope.$watch('currentBase', function(newValue, oldValue){
                    var t = 86400000
                    var yesterday = new Date(new Date() - t * 1)
                    if(newValue === 'date'){ // 不做操作，只是更新
                        watchFn(newValue, oldValue)
//                      var num = 7
//                      var beginDate = new Date(yesterday - t*(num-1)),
//                          endDate = yesterday
//                      scope.intervalCalendar.begin.dateStr = date2str(beginDate)
//                      scope.intervalCalendar.end.dateStr = date2str(endDate)
                    } else if(newValue === 'month'){ // 若为最近7天则切换成30天
                        if(scope.currentInterval == 7){
                            scope.intervalFns[30]()
                        } else {
                            watchFn(newValue, oldValue)
                        }
//                      var now = new Date()
//                      now.setMonth(now.getMonth()-1)
//                      now.setDate(1)
//                      var lastMonthFirstDay = now
//                      scope.intervalCalendar.begin.dateStr = date2str(lastMonthFirstDay)
//                      scope.intervalCalendar.end.dateStr = date2str(yesterday)
                    }
                })
                function reload(){
                    var product = scope.currentProduct,
                        startDate = scope.intervalCalendar.begin.dateStr,
                        endDate = scope.intervalCalendar.end.dateStr
                    if(!product || !startDate || !endDate){
                        return false;
                    }
                    var data = getData(product, startDate, endDate)
                    data.$promise.then(function(){
                        reloadChart(handledData)
//                      return handledData
                    })
                }
                var handledData // getData后会把结果放到这里
                var oldData // 暂时存放旧的data
                function dataHandler(data){
                    var x = [], y = []
                    $.each(data, function(index, value){
                        x.push(value.date)
                        y.push(value.count)
                    })
                    return {
                        x: x,
                        y: y
                    }
                }
                function getData(){
                    // 先隐藏无数据提示，显示出echart容器
                    $('.echart').show()
                    $('.noData').hide()
                    // 使用scope.currentProduct等信息用ajax获取数据... 
                    var data = byDateResource.post({productType: scope.converter('pageType', scope.currentProduct), baseType: scope.converter('baseType', scope.currentBase)}, {
                        start: scope.intervalCalendar.begin.dateStr, end: scope.intervalCalendar.end.dateStr
                    })
                    data.$promise.then(function(data){
                        oldData = data
                        handledData = dataHandler(data)
                        return handledData // 不知为何不能传到下一个then中，姑且使用外部变量传值
                    })
                    return data
                }
                function reloadChart(data){
                    // 重载图表
                    if(!data) return false
                    var theme = {
                        color:['#52C4EB']
                    }
                    var option = chart.getOption()
                    if(!handledData.x.length || !handledData.y.length){
                        // 无数据，显示提示
                        $('.echart').hide()
                        $('.noData').show()
                        return false;
                    }
                    option.xAxis[0].data = handledData.x
                    option.series[0].data = handledData.y
                    
                    chart.setOption(option, true).setTheme(theme)
                }
                
                function createChart(){
                    var data = getData()
                    var active_day_num_myChart = echarts.init(document.getElementById('active_day_num'));
                    data.$promise.then(function(){
                        var data = handledData
                        var active_day_num_option = {
                            color:['#52C4EB'],
                            tooltip : {
                                trigger: 'axis'
                            },
                            legend: {
                                data:['活跃设备数']
                            },
                            toolbox: {
                                show : false,
                                feature : {
                                    mark : {show: true},
                                    dataView : {show: true, readOnly: false},
                                    magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                                    restore : {show: true},
                                    saveAsImage : {show: true}
                                }
                            },
                            calculable : true,
                            xAxis : [
                                {
                                    type : 'category',
                                    boundaryGap : false,
                                    data : data.x
                                }
                            ],
                            yAxis : [
                                {
                                    type : 'value'
                                }
                            ],
                            series : [
                                {
                                    name:'活跃设备数',
                                    type:'line',
                                    stack: '总量',
                                    itemStyle: {normal: {areaStyle: {type: 'default'}}},
                                    data: data.y
                                }
                            ]
                        };
                        //为echarts对象加载数据
                        active_day_num_myChart.setOption(active_day_num_option);
                    })
                    return active_day_num_myChart
                }
            }
        }
    }])
    .directive('basicTrend', ['byDateResource', function(byDateResource){
        return {
            restrict: 'A',
            link: function(scope, elem, attrs){
                $(document).ready(function () {
                    var width = $(".warp").width() - 41
                    $(".warp").width(width)
                    $(".warp_content").width(width);
                    $('#header').css('min-width', width)
                });
                
                
                function watchFn(newValue, oldValue){
                    if(newValue === oldValue)
                        return false;
                    if(!chart){
                        chart = createChart()
                    } else {
                        reload()
                    }
                }
                scope.currentSign = 'register'
                var chart = createChart()
                
                scope.$watch('currentProduct', watchFn)
                scope.$watch('intervalCalendar', watchFn, true)
                
                function date2str(dateObj){
                    var y = dateObj.getFullYear(),
                        m = dateObj.getMonth() + 1,
                        d = dateObj.getDate()
                    if(m<10) 
                        m = '0' + m
                    if(d<10)
                        d = '0' + d
                    return y+'-'+m+'-'+d
                }
                var signs = scope.signs = {
                    register: {name: '注册', legend: '新增注册数'},
                    install: {name: '安装', legend: '新增安装数'},
                    loging: {name: '登录', legend: '当天登录数'}
                }
                function reload(){
                    var product = scope.currentProduct,
                        startDate = scope.intervalCalendar.begin.dateStr,
                        endDate = scope.intervalCalendar.end.dateStr
                    if(!product || !startDate || !endDate){
                        return false;
                    }
                    var data = getData()
                    data.$promise.then(function(){
                        reloadChart(handledData)
//                      return handledData
                    })
                }
                var handledData // getData后会把结果放到这里
                var oldData // 暂时存放旧的data
                function dataHandler(data){
                    var x = [], y = []
                        
                    $.each(data, function(index, value){
                        x.push(value.date)
                        y.push(value[scope.currentSign])
                    })
                    return {
                        x: x,
                        y: y
                    }
                }
                function swicthSign(){ // 这里许多代码间的交互本应该传值，但是使用了共享外部变量的方式
                    if(!oldData) return false;
                    handledData = dataHandler(oldData)
                    reloadChart(handledData)
                }
                scope.$watch('currentSign', function(newValue, oldValue){
                    if(newValue === oldValue)
                        return false;
                    swicthSign()
                })
                function getData(){
                    // 先隐藏无数据提示，显示出echart容器
                    $('.echart').show()
                    $('.noData').hide()
                    // 使用scope.currentProduct等信息用ajax获取数据... 
                    var data = byDateResource.post({productType: scope.converter('pageType', scope.currentProduct), baseType: scope.converter('baseType', 'date')}, {start: scope.intervalCalendar.begin.dateStr, end: scope.intervalCalendar.end.dateStr}, function(){
                    }, function(){
                        $('.noData').show()                     
                    })
                    data.$promise.then(function(data){
                        oldData = data
                        handledData = dataHandler(data)
                        return handledData // 不知为何不能传到下一个then中，姑且使用外部变量传值
                    })
                    return data
                }
                function reloadChart(data){
                    // 重载图表
                    if(!data) return false
                    var theme = {
                        color:['#52C4EB']
                    }
                    var option = chart.getOption()
                    if(!handledData.x.length || !handledData.y.length){
                        // 无数据，显示提示
                        $('.echart').hide()
                        $('.noData').show()
                        return false;
                    }
                    option.legend.data = [signs[scope.currentSign].legend]
                    option.xAxis[0].data = handledData.x
                    option.series[0].data = handledData.y
                    option.series[0].name = signs[scope.currentSign].legend
                    
                    chart.setOption(option, true).setTheme(theme)
                }
                
                function createChart(){
                    var data = getData()
                    var trend_num_myChart = echarts.init(document.getElementById('trend_num'));
                    data.$promise.then(function(){
                        var data = handledData
                        if(!handledData.x.length || !handledData.y.length){
                            // 无数据，显示提示
                            $('.echart').hide()
                            $('.noData').show()
                            return false;
                        }
                        var trend_num_option = {
                            color:['#52c4bb'],
                            tooltip : {
                                trigger: 'axis'
                            },
                            legend: {
                                data:[signs[scope.currentSign].legend]
                            },
                            toolbox: {
                                show : false,
                                feature : {
                                    mark : {show: true},
                                    dataView : {show: true, readOnly: false},
                                    magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                                    restore : {show: true},
                                    saveAsImage : {show: true}
                                }
                            },
                            calculable : true,
                            xAxis : [
                                {
                                    type : 'category',
                                    boundaryGap : false,
                                    data : data.x
                                }
                            ],
                            yAxis : [
                                {
                                    type : 'value'
                                }
                            ],
                            series : [
                                {
                                    name:signs[scope.currentSign].legend,
                                    type:'line',
                                    stack: '总量',
                                    itemStyle: {normal: {areaStyle: {type: 'default'}}},
                                    data: data.y
                                }
                            ]
                        };
                        trend_num_myChart.setOption(trend_num_option);
                    })
                    return trend_num_myChart
                }
                //查看趋势分析指标：注册 安装 登录 策略
                $("#trend .button").click(function () {
                    $(".hide_button").toggle();
                });
            }
        }
    }])
    .directive('usersTerritory', ['usersTerritoryResource', function(usersTerritoryResource){
        return {
            restrict: 'A',
            link: function(scope, elem, attrs){
                $(document).ready(function () {
                    var width = $(".warp").width() - 41
                    $(".warp").width(width)
                    $(".warp_content").width(width);
                    $('#header').css('min-width', width)
                });
                
                var vm = scope.vm = {}
                vm.data = usersTerritoryResource.get()
                var chart 
                vm.data.$promise.then(function(data){
                    chart = createChart(data)
                })
                function handleData(data){
                    // 使用scope.currentProduct等信息用ajax获取数据... 
                    var total = 0
                    $.each(data, function(index, province){
                        var lastWord = province.name[province.name.length - 1]
                        if(lastWord === '市' || lastWord === '省'){
                            province.name = province.name.slice(0, province.name.length-1)
                        }
                        province.value = parseInt(province['val_num'])
                        total += province.value
                    })
                    $.each(data, function(index, province){
                        province.percent = (province.value * 100 / total).toFixed(2)
                    })
//                  vm.data = [].slice.call(data, 0)
                    vm.data = data
                    
                    return vm.data
                }
                function createChart(data){
                    if(!data) return false;
                    data = handleData(data)
                    var territory_map_myChart = echarts.init(document.getElementById('territory_map'));
                    var territory_map_option = {
                        tooltip : {
                            trigger: 'item',
                            formatter: function(params){
                                var legend  = params[0],
                                    place = params[1],
                                    obj = params[5]
                                if(!obj.percent){
                                    return '暂无数据'
                                }
                                return legend + '<br />' + place + ' : ' + obj.percent + '%'
                            }
                        },
                        legend: {
                            show: false,
                            orient: 'vertical',
                            x:'left',
                            data:['安装量']
                        },
                        toolbox: {
                            show: false,
                            orient : 'vertical',
                            x: 'right',
                            y: 'center',
                            feature : {
                                mark : {show: true},
                                dataView : {show: true, readOnly: false},
                                restore : {show: true},
                                saveAsImage : {show: true}
                            }
                        },
                        roamController:{
                            show: false,
                            x: 'right',
                            mapTypeControl: {
                                'china': true
                            }
                        },
                        dataRange: {
                            show: false,
                            x: 'left',
                            y: 'bottom',
                            splitList: [
                                {start: 100000, color:'#006EDD'},
                                {start: 50000, end: 100000, color:'#328de6'},
                                {start: 10000, end: 50000, color:'#51a1e6'},
                                {start: 1000, end: 10000, color:'#75b7f1'},
                                {start: 500, end: 1000,color:'#94d0f4'},
                                {start: 0, end: 500, color: '#bde6f8'}
                            ],
                            color: ['#E0022B', '#E09107', '#A3E00B']
                        },
                        series : [
                            {
                                name: '安装量',
                                type: 'map',
                                mapType: 'china',
                                roam: false,
                                itemStyle:{
                                    normal:{
                                        label:{
                                            show:true
                                        }
                                    },
                                    emphasis:{label:{show:true}}
                                },
                                data: data
                            }
                        ]
                    };
                    territory_map_myChart.setOption(territory_map_option);
                    return territory_map_myChart
                }
            }
        }
    }])
    .directive('usersTerminal', ['usersTerminalResource', function(usersTerminalResource){
        return {
            restrict: 'A',
            link: function(scope, elem, attrs){
                $(document).ready(function () {
                    var width = $(".warp").width() - 41
                    $(".warp").width(width)
                    $(".warp_content").width(width);
                    $('#header').css('min-width', width)
                });
                
                var chart
                var vm = scope.vm = {}
                vm.data = usersTerminalResource.get()
                vm.data.$promise.then(function(data){
                    data = handleData(data)
                    chart = createChart(data) 
                })
                function handleData(data){
                    var result = {}
                    var types = ['equipment', 'processor_brand', 'disk']
                    $.each(types, function(index, type){
                        result[type] = {
                            data: [],
                            legend: [],
                            series: []
                        }
                    })
                    $.each(data, function(index, value){
                        var type = value.type
//                      result[type].data.push(value)
                        result[type].legend.push(value.name)
                        result[type].series.push({
                            name: value.name,
                            value: parseFloat(value.val_percent)
                        })
                    })
                    return result
                }
                function createChart(datas){
                    
                    var terminal_memory_myChart = echarts.init(document.getElementById('terminal_memory'));
                    var terminal_cpu_myChart = echarts.init(document.getElementById('terminal_cpu'));
                    var terminal_harddisk_myChart = echarts.init(document.getElementById('terminal_harddisk'));
                    var terminal_memory_option = {
                        color:['#52c4eb','#6999d2','#5fc2a8','#38bb99'],
                        tooltip : {
                            trigger: 'item',
                            formatter: "{a} <br/>{b} : {c}%"
                        },
                        legend: {
                            show : false,
                            orient : 'vertical',
                            x : 'left',
                            data:datas.equipment.legend
                        },
                        calculable : false,
                        series : [
                            {
                                name:'设备内存',
                                type:'pie',
                                radius : ['30%', '60%'],
                                itemStyle : {
                                    normal : {
                                        label : {
                                            show : true,
                                            textStyle:{
                                                fontSize : '18',
                                                color:'#000'
                                            }
                                        },
                                        labelLine : {
                                            show : true,
                                            length:30,
                                            lineStyle:{
                                                width:3,
                                                type:'solid'
                                            }
                    
                                        }
                                    },
                                    emphasis : {
                                        label : {
                                            show : true,
                                            position : 'center',
                                            textStyle : {
                                                fontSize : '24',
                                                fontWeight : 'bold'
                                            }
                                        }
                                    }
                                },
                                data:datas.equipment.series
                            }
                        ]
                    };
                    var terminal_cpu_option = {
                        color:['#a2ce6f','#fcce60'],
                        tooltip : {
                            trigger: 'item',
                            formatter: "{a} <br/>{b} : {c}%"
                        },
                        legend: {
                            show : false,
                            orient : 'vertical',
                            x : 'left',
                            data: datas.processor_brand.legend
                        },
                        calculable : false,
                        series : [
                            {
                                name:'处理器品牌',
                                type:'pie',
                                radius : ['30%', '60%'],
                                itemStyle : {
                                    normal : {
                                        label : {
                                            show : true,
                                            textStyle:{
                                                fontSize : '18',
                                                color:'#000'
                                            }
                                        },
                                        labelLine : {
                                            show : true,
                                            length:30,
                                            lineStyle:{
                                                width:3,
                                                type:'solid'
                                            }
                    
                                        }
                                    },
                                    emphasis : {
                                        label : {
                                            show : true,
                                            position : 'center',
                                            textStyle : {
                                                fontSize : '24',
                                                fontWeight : 'bold'
                                            }
                                        }
                                    }
                                },
                                data: datas.processor_brand.series
                            }
                        ]
                    };
                    var terminal_harddisk_option = {
                        color:['#ec5868','#da4656'],
                        tooltip : {
                            trigger: 'item',
                            formatter: "{a} <br/>{b} : {c}%"
                        },
                        legend: {
                            show : false,
                            orient : 'vertical',
                            x : 'left',
                            data: datas.disk.legend
                        },
                        calculable : false,
                        series : [
                            {
                                name:'硬盘',
                                type:'pie',
                                radius : ['30%', '60%'],
                                itemStyle : {
                                    normal : {
                                        label : {
                                            show : true,
                                            textStyle:{
                                                fontSize : '18',
                                                color:'#000'
                                            }
                                        },
                                        labelLine : {
                                            show : true,
                                            length:30,
                                            lineStyle:{
                                                width:3,
                                                type:'solid'
                                            }
                    
                                        }
                                    },
                                    emphasis : {
                                        label : {
                                            show : true,
                                            position : 'center',
                                            textStyle : {
                                                fontSize : '14',
                                                fontWeight : 'bold'
                                            }
                                        }
                                    }
                                },
                                data: datas.disk.series
                            }
                        ]
                    };
                    //为echarts对象加载数据
                    terminal_memory_myChart.setOption(terminal_memory_option);
                    terminal_cpu_myChart.setOption(terminal_cpu_option);
                    terminal_harddisk_myChart.setOption(terminal_harddisk_option);
                }
            }
        }
    }])
    .controller('reportCtrl', ['$scope', '$routeParams', '$log', 'deepCopy', 'orderBy', function($scope, $routeParams, $log, deepCopy, orderBy){
        $scope.activePage = $routeParams.pageType
        $scope.activeDimension = $routeParams.dimension
        var vm = $scope.vm = {}
        vm.totalSize = 0;
        vm.curPage = 0;
        vm.perPage = 20;
        $scope.initTableHeads = function(order){
            var self = this
            return $.map(order, function(hashKey) {
            	return self.tableHeadHash[hashKey]
            })
        }
        $scope.functionType = 'report'
        $scope.reloadData = function(){
            var self = this
            var data = this.getDatas.apply(this, arguments)
            data.$promise.then(function(n){
                orderBy(data, self.orderKey, null, self.reverse)
                self.data = data
            })
            return data
//          data.promise.then(function(data){
//          })
        }
        void function($scope){
            var obj = {
                pageType: {
                    duLiBan: 'timeon',
                    heZuoBan: 'timeoneqq',
                    yunShaDu: 'cloud'
                },
                baseType: {
                    date: 'dayActive',
                    week: 'weekActive',
                    month: 'monthActive'
                }
            }
            $scope.converter = function(type, key){
                var value = obj[type] && obj[type][key]
                return value ? value : key
            }
        }($scope)
    }])
    .controller('dimension', ['$scope', 'byDateResource', function($scope, byDateResource){
        var getStrFromSelectedTime = function(selectedTime){
            var dateStr = ''
            var i, o = selectedTime
            for(i in o){
                o = o[i]
                dateStr += i
            }
            for(i in o){
                o = o[i]
                dateStr += '-' + (parseInt(i) + 1)
            }
            for(i in o){
                o = o[i]
                dateStr += '-' + i
            }
            return dateStr
        }
        $scope.initCalendarSettings = function(key){
            var yesterday = new Date(new Date() - 86400000)
            return {
                year: parseInt(/^\d{4}/.exec($scope.intervalCalendar[key].dateStr)[0]),
                month: parseInt(/^\d{4}-(\d{1,2})/.exec($scope.intervalCalendar[key].dateStr)[1] - 1),
                getCalendar: function(calendar){
                    var obj = $scope.intervalCalendar[key]
                    obj.calendar = calendar
                    obj.watcher && obj.watcher()
                    obj.watcher = $scope.$watch('intervalCalendar.' + key + '.calendar.selectedTime', function(newValue, oldValue){
                        if(newValue === oldValue) return false;
                        $scope.intervalCalendar[key].dateStr = getStrFromSelectedTime(newValue)
                    }, true)
                },
                settings: {
                    endDate: yesterday.getFullYear() + '-' + (yesterday.getMonth() + 1) + '-' + yesterday.getDate()
                },
                callback: function(calendar){
                    var date
                    if(date = parseInt(/\d{1,2}$/.exec($scope.intervalCalendar[key].dateStr)[0]))
                    calendar.select(date)
                }
            }
        }
        var getTimeFromStr = function(str){
            var monthRegexpString = '^(\\d{4})-(\\d{1,2})',
                dateRegexpString = monthRegexpString + '-(\\d{1,2})',
                monthRegexp = new RegExp(monthRegexpString),
                dateRegexp = new RegExp(dateRegexpString)
            var result, year, month, date
            var arr = []
            result = dateRegexp.exec(str)
            if(!result)
                result = monthRegexp.exec(str)
            if(!result) return arr;
            year = parseInt(result[1])
            month = parseInt(result[2] - 1)
            date = parseInt(result[3])
            arr.push(year)
            arr.push(month)
            if(date)
                arr.push(date)
            return arr
        }
        $.each(['start', 'end'], function(i, key){
            $scope.$watch('intervalCalendar.' + key + '.dateStr', function(newValue, oldValue){
                if(newValue === oldValue) return false;
                var dateArr = getTimeFromStr(newValue)
                var calendar = $scope.intervalCalendar[key].calendar
                // 防止2016-3-9与2016-03-09被认为是不同日期
                if(dateArr.length === 3){
                    var dateObj = {}
                        dateObj[dateArr[0]] = {}
                        dateObj[dateArr[0]][dateArr[1]] = {}
                        dateObj[dateArr[0]][dateArr[1]][dateArr[2]] = true
                    var inputDateStr = getStrFromSelectedTime(dateObj),
                        calendarDateStr = getStrFromSelectedTime(calendar.selectedTime)
                    if(inputDateStr === calendarDateStr) return false;
                }
                if(!dateArr.length) return false;
                calendar.setTime(dateArr[0], dateArr[1])
                if(dateArr.length === 3) { // 说明有year、month、date，应对日历做选择操作
                    // 日期超出本月最后日期则恢复成原日期
                    calendar.setTime(dateArr[0], dateArr[1])
                    var date = calendar.getShowedDate(dateArr[2])
                    if(!date) {
                        var oldDate = /-(\d{1,2})$/.exec(oldValue)[1]
                        $scope.intervalCalendar[key].dateStr = dateArr[0] + '-' + (dateArr[1] + 1) + '-' + oldDate
                        return false;
                    }
                    calendar.unselectAll()
                    calendar.select(dateArr[2])
                }
            })
        })
        void function(){
            var regexp = /\d{1,2}-\d{1,2}$/
            var initTimeData = function(dateStr){
                return regexp.exec(dateStr)[0]
            }
            $scope.baseType = 'date'
            $scope.baseTypes = {
                date: {
                    name: '日活',
                    initTimeData: initTimeData
                },
                week: {
                    name: '周活',
                    initTimeData: initTimeData
                },
                month: {
                    name: '月活',
                    initTimeData: initTimeData
                }
            }
        }()
        
        void function($scope){
            var dateInterval = 7
            var now = new Date(),
                startDate = new Date(now - 86400000 * dateInterval),
                endDate = new Date(now - 86400000)
            var getStrFromDate = function(date){
                var year = date.getFullYear(),
                    month = date.getMonth() + 1,
                    date = date.getDate()
                var str = [year, month, date].join('-')
                return str
            }
            $scope.intervalCalendar.begin.dateStr = getStrFromDate(startDate)
            $scope.intervalCalendar.end.dateStr = getStrFromDate(endDate)
        }($scope)
    }])
    .controller('dimensionByDate', ['$scope', 'byDateResource', function($scope, byDateResource){
        $scope.getDatas = function(startDate, endDate, baseType){
            var converter = this.converter
            var data = byDateResource.post({pageType: converter('pageType', $scope.activePage), baseType: converter('baseType', baseType)}, {start: startDate, end: endDate})
            return data
        }
        $scope.data = []
        $scope.orderKey = 'date'
        $scope.reverse = false
        $scope.tableSettings = {
            orderKey: $scope.orderKey,
            reverse: $scope.reverse
        }
        $scope.tableHeadHash = {
            date: {name: '日期'},
            count: {name: '活跃数'},
            install: {name: '安装'},
            register: {name: '注册企业'},
            all_enterprises: {name: '总企业数'},
            all_devices: {name: '总设备'}
        }
        var i
        for(i in $scope.tableHeadHash){
            $scope.tableHeadHash[i]['key'] = i
        }
        $scope.tableHeadsOrder = ['date', 'count', 'install', 'register', 'all_enterprises', 'all_devices']
        $scope.tableHeads = $scope.initTableHeads($scope.tableHeadsOrder)
        $scope.intervalCalendar = {
            start: {
                dateStr: '',
                calendar: null
            },
            end: {
                dateStr: '',
                calendar: null
            }
        }
        var getStrFromSelectedTime = function(selectedTime){
            var dateStr = ''
            var i, o = selectedTime
            for(i in o){
                o = o[i]
                dateStr += i
            }
            for(i in o){
                o = o[i]
                dateStr += '-' + (parseInt(i) + 1)
            }
            for(i in o){
                o = o[i]
                dateStr += '-' + i
            }
            return dateStr
        }
        $scope.initCalendarSettings = function(key){
            var yesterday = new Date(new Date() - 86400000)
            return {
                year: parseInt(/^\d{4}/.exec($scope.intervalCalendar[key].dateStr)[0]),
                month: parseInt(/^\d{4}-(\d{1,2})/.exec($scope.intervalCalendar[key].dateStr)[1] - 1),
                getCalendar: function(calendar){
                    var obj = $scope.intervalCalendar[key]
                    obj.calendar = calendar
                    obj.watcher && obj.watcher()
                    obj.watcher = $scope.$watch('intervalCalendar.' + key + '.calendar.selectedTime', function(newValue, oldValue){
                        if(newValue === oldValue) return false;
                        $scope.intervalCalendar[key].dateStr = getStrFromSelectedTime(newValue)
                    }, true)
                },
                settings: {
                    endDate: yesterday.getFullYear() + '-' + (yesterday.getMonth() + 1) + '-' + yesterday.getDate()
                },
                callback: function(calendar){
                    var date
                    if(date = parseInt(/\d{1,2}$/.exec($scope.intervalCalendar[key].dateStr)[0]))
                    calendar.select(date)
                }
            }
        }
        var getTimeFromStr = function(str){
            var monthRegexpString = '^(\\d{4})-(\\d{1,2})',
                dateRegexpString = monthRegexpString + '-(\\d{1,2})',
                monthRegexp = new RegExp(monthRegexpString),
                dateRegexp = new RegExp(dateRegexpString)
            var result, year, month, date
            var arr = []
            result = dateRegexp.exec(str)
            if(!result)
                result = monthRegexp.exec(str)
            if(!result) return arr;
            year = parseInt(result[1])
            month = parseInt(result[2] - 1)
            date = parseInt(result[3])
            arr.push(year)
            arr.push(month)
            if(date)
                arr.push(date)
            return arr
        }
        $.each(['start', 'end'], function(i, key){
            $scope.$watch('intervalCalendar.' + key + '.dateStr', function(newValue, oldValue){
                if(newValue === oldValue) return false;
                var dateArr = getTimeFromStr(newValue)
                var calendar = $scope.intervalCalendar[key].calendar
                // 防止2016-3-9与2016-03-09被认为是不同日期
                if(dateArr.length === 3){
                    var dateObj = {}
                        dateObj[dateArr[0]] = {}
                        dateObj[dateArr[0]][dateArr[1]] = {}
                        dateObj[dateArr[0]][dateArr[1]][dateArr[2]] = true
                    var inputDateStr = getStrFromSelectedTime(dateObj),
                        calendarDateStr = getStrFromSelectedTime(calendar.selectedTime)
                    if(inputDateStr === calendarDateStr) return false;
                }
                if(!dateArr.length) return false;
                calendar.setTime(dateArr[0], dateArr[1])
                if(dateArr.length === 3) { // 说明有year、month、date，应对日历做选择操作
                    // 日期超出本月最后日期则恢复成原日期
                    calendar.setTime(dateArr[0], dateArr[1])
                    var date = calendar.getShowedDate(dateArr[2])
                    if(!date) {
                        var oldDate = /-(\d{1,2})$/.exec(oldValue)[1]
                        $scope.intervalCalendar[key].dateStr = dateArr[0] + '-' + (dateArr[1] + 1) + '-' + oldDate
                        return false;
                    }
                    calendar.unselectAll()
                    calendar.select(dateArr[2])
                }
            })
        })
        void function(){
            var regexp = /\d{1,2}-\d{1,2}$/
            var initTimeData = function(dateStr){
                return regexp.exec(dateStr)[0]
            }
            $scope.baseType = 'date'
            $scope.baseTypes = {
                date: {
                    name: '日活',
                    initTimeData: initTimeData
                },
                week: {
                    name: '周活',
                    initTimeData: initTimeData
                },
                month: {
                    name: '月活',
                    initTimeData: initTimeData
                }
            }
        }()
        void function($scope){
            var resourceValues = ['intervalCalendar.begin.dateStr', 'intervalCalendar.end.dateStr', 'baseType']
            var lastValues = []
            var startDate, endDate, hasChecked = false
            var checkValues = function(changedStr, newValue){
                if(changedStr === 'baseType' && !startDate && !endDate){
                    if(newValue === 'date'){
                        var now = new Date()
                        startDate = new Date(now - 86400000 * 7)
                        endDate = new Date(now - 86400000)
                        startDate = startDate.getFullYear() + '-' + (startDate.getMonth() + 1) + '-' + startDate.getDate()
                        endDate = endDate.getFullYear() + '-' + (endDate.getMonth() + 1) + '-' + endDate.getDate()
                        $scope.intervalCalendar.begin.dateStr = startDate
                        $scope.intervalCalendar.end.dateStr = endDate
                        if(!hasChecked) {
                            startDate = null
                            endDate = null
                            hasChecked = true
                        }
                        return false;
                    } else if(newValue === 'week'){
                        var now = new Date()
                        startDate = new Date(now - 86400000 * 49)
                        endDate = new Date(now - 86400000)
                        startDate = startDate.getFullYear() + '-' + (startDate.getMonth() + 1) + '-' + startDate.getDate()
                        endDate = endDate.getFullYear() + '-' + (endDate.getMonth() + 1) + '-' + endDate.getDate()
                        $scope.intervalCalendar.begin.dateStr = startDate
                        $scope.intervalCalendar.end.dateStr = endDate
                        if(!hasChecked) {
                            startDate = null
                            endDate = null
                            hasChecked = true
                        }
                        return false;
                    } else if(newValue === 'month'){
                        var now = new Date(),
                            thisYear = now.getFullYear(),
                            thisMonthFirstDay = new Date(thisYear + '-' + (now.getMonth() + 1) + '-01'),
                            prevMonthLastDay = new Date(thisMonthFirstDay - 86400000),
                            prevMonthLastDay_year = prevMonthLastDay.getFullYear()
                        if(prevMonthLastDay_year < thisYear){
                            endDate = now
                        } else {
                            endDate = prevMonthLastDay
                        }
                        endDate = endDate.getFullYear() + '-' + (endDate.getMonth() + 1) + '-' + endDate.getDate()
                        startDate = thisYear + '-' + '01-01'
                        $scope.intervalCalendar.begin.dateStr = startDate
                        $scope.intervalCalendar.end.dateStr = endDate
                        if(!hasChecked) {
                            startDate = null
                            endDate = null
                            hasChecked = true
                        }
                        return false;
                    }
                } else {
                    startDate = null
                    endDate = null
                }
                var arr = []
                for(var i = 0, str, value;str = resourceValues[i];++i){
                    value = $scope.$eval(str)
                    if(!value) return false;
                    arr.push(value)
                }
                var same = true
                for(i = 0;i < arr.length;++i){
                    if(arr[i] != lastValues[i]){
                        same = false
                        break
                    }
                }
                lastValues = arr
                if(same) return false;
                return arr
            }
            for(var i = 0, str, value;str = resourceValues[i];++i){
                void function(str){
                    $scope.$watch(str, function(newValue, oldValue){
                        if(!newValue) return false;
                        var values = checkValues(str, newValue)
                        if(!values) return false;
                        $scope.reloadData.apply($scope, values)
                    })
                }(str)
            }
        }($scope)
        void function($scope){
            var dateInterval = 7
            var now = new Date(),
                startDate = new Date(now - 86400000 * dateInterval),
                endDate = new Date(now - 86400000)
            var getStrFromDate = function(date){
                var year = date.getFullYear(),
                    month = date.getMonth() + 1,
                    date = date.getDate()
                var str = [year, month, date].join('-')
                return str
            }
            $scope.intervalCalendar.begin.dateStr = getStrFromDate(startDate)
            $scope.intervalCalendar.end.dateStr = getStrFromDate(endDate)
        }($scope)
    }])
    .controller('dimensionByCompany', ['$scope', 'byCompanyResource', function($scope, byCompanyResource){
        $scope.getDatas = function(baseType){
            var converter = this.converter
            var top
            var UpperCase = baseType.replace(/^(\w)/,function(v){return v.toUpperCase()})
            if(this.activePage === 'heZuoBan'){
                top = 'top1000' + UpperCase
            } else {
                top = 'top100' + UpperCase
            }
            var data = byCompanyResource.post({pageType: converter('pageType', this.activePage), top: top}, {})
            data.$promise.then(function(n){
                var regexp = / \d{2}:\d{2}:\d{2}$/
                $.each(n, function(i, value){
                    $.each(['date', 'last_login', 'register_date'], function(i, key){
                        if(value[key])
                            value[key] = value[key].replace(regexp, '')
                    })
                })
            })
            return data
        }
        $scope.data = []
        $scope.orderKey = 'count'
        $scope.reverse = true
        $scope.tableSettings = {
            orderKey: $scope.orderKey,
            reverse: $scope.reverse
        }
        if($scope.activePage === 'heZuoBan'){
            $scope.baseUrl = '/Manage/authEqq/'
        } else if($scope.activePage === 'duLiBan') {
            $scope.baseUrl = '/Manage/authorise/'
        }
        $scope.tableHeadHash = {
            name: {name: '企业名称'},
            register_date: {name: '注册时间'},
            clients: {name: '总客户端数'},
            install: {name: '新增客户端数'},
            count: {name: '近期活跃'}
        }
        $scope.tableHeadsOrder = ['name', 'register_date', 'clients', 'install', 'count']
        if($scope.activePage === 'yunShaDu'){
            $scope.tableHeadHash = {
                cid: {name: 'cid'},
                register_date: {name: '注册时间'},
                last_login: {name: '最近登录时间'},
                count: {name: '安装客户端数'}
            }
            $scope.tableHeadsOrder = ['cid', 'register_date', 'last_login', 'count']
        }
        var i
        for(i in $scope.tableHeadHash){
            $scope.tableHeadHash[i]['key'] = i
        }
        $scope.tableHeads = $scope.initTableHeads($scope.tableHeadsOrder)
        $scope.baseType_company_map = {
            week: {value: 'week', text: '周'},
            month: {value: 'month', text: '月'}
        }
//      $scope.baseType_company设为数组如['week', 'month']则显示下拉菜单，设为null则不显示下拉菜单而是使用currentBaseType的值。
//      $scope.currentBaseType = 'week'
//      $scope.baseType_company = ['week']
        $scope.currentBaseType = 'month'
        $scope.baseType_company = null
//      if($scope.activePage === 'yunShaDu'){
//          // 云杀毒有下拉菜单
//          $scope.baseType_company.push('month')
//      } else {
//          // 其他不显示下拉菜单
//          $scope.baseType_company = null
//      }
        $scope.$watch('currentBaseType', function(newValue, oldValue){
            if(!newValue) return false;
            $scope.reloadData($scope.currentBaseType)
        })
    }])
    .directive('sidebar', [function(){
        var pages = [
            {type: 'heZuoBan', text: 'TimeOn合作版'},
            {type: 'duLiBan', text: 'TimeOn独立版'},
            {type: 'yunShaDu', text: 'TimeOn云杀毒'},
            {type: 'yunBeiFen', text: 'TimeOn云备份', glass: 'disable'}
        ]
        return {
            restrict: 'A',
            scope: true,
            templateUrl: '/js/apps/main/tpl/sidebar.html?v=20161114',
            link: function(scope, elem, attrs){
                scope.pages = pages
                elem.show()
                elem.on('click', '.disable', function(){
                    return false;
                })
            }
        }
    }])
    .directive('singleCalendarCtrl', function(){
        return {
            restrict: 'A',
            link: function(scope, elem, attrs){
                var calendar = elem.find('.calendar'),
                    input = elem.find('.dateSelector')
                var calendarClick = false
                input.on('focus', function(){
                    calendar.show()
                })
                $(document).click(function(e){
                    if(calendar.css('display') === 'none') return ;
                    var obj = $(e.target);
                    if ($(obj).is(elem) || $(obj).is(elem.find('*'))) {
                        input.focus()
                    } else {
                        calendar.hide()
                    }
                });
            }
        }
    })
    .directive('chartTrend', ['shallowCopy', 'isEmptyObject', 'orderBy', function(shallowCopy, isEmptyObject, orderBy){
        return {
            restrict: 'A',
            link: function(scope, elem ,attrs){
                var dataKey = attrs['chartTrend']
                var myChart = echarts.init(elem.context)
                var handleData = function(data){
                    data = shallowCopy(data)
                    orderBy(data, 'date')
                    var timeData = [], valueDatas = []
                    var hasHandleTime = false
                    $.each(['count', 'all_enterprises', 'all_devices'], function(index, key){
                        var arr = []
                        valueDatas.push(arr)
                        $.each(data, function(i, value){
                            if(!hasHandleTime)
                                timeData.push(scope.baseTypes[scope.baseType].initTimeData(value.date))
                            arr.push(parseInt(value[key]))
                        })
                        hasHandleTime = true
                    })
                    return {
                        timeData: timeData, 
                        valueDatas: valueDatas
                    }
                }
                scope.initChart = function(data, settings){
                    if(!data || !data.length) {
                        return false;
                    }
                    var handledData = handleData(data)
                    settings.timeData = handledData.timeData
                    settings.valueDatas = handledData.valueDatas
                    settings.legendNames.push('总企业数')
                    settings.legendNames.push('总设备数')
                    initLine(myChart, settings)
                }
                scope.reloadChart = function(data){
                    if(!data || !data.length) return false;
                    var theme = {
                        color: [
                            '#FFD860','#9BCA63','#2c71b5'
                        ]
                    };
                    var handledData = handleData(data)
                    var name = scope.baseTypes[scope.baseType].name
                    var option = myChart.getOption()
                    if(isEmptyObject(option)){
                        scope.initChart(data, {
                            legendNames: [scope.baseTypes[scope.baseType].name]
                        })
                        return false;
                    }
                    option.xAxis[0].data = handledData.timeData
                    option.series[0].data = handledData.valueDatas[0]
                    option.series[0].name = name
                    option.series[1].data = handledData.valueDatas[1]
                    option.series[1].name = '总企业数'
                    option.series[2].data = handledData.valueDatas[2]
                    option.series[2].name = '总设备数'
                    option.legend.data = [name, '总企业数', '总设备数']
                    myChart.setOption(option, true).setTheme(theme)
                }
                var notInit = true
                scope.$watch(dataKey, function(newValue, oldValue){
                    if(!newValue) return false;
                    if(notInit){ // 说明是第一次渲染
                        if(scope.initChart(newValue, {
                            legendNames: [scope.baseTypes[scope.baseType].name]
                        }) === false){
                            notInit = true
                            $('.chart-trend-noData').css('visibility', 'visible')
                            return;
                        } else {
                            notInit = false
                        }
                    } else {
                        scope.reloadChart(newValue)
                    }
                    $('.chart-trend-noData').css('visibility', 'hidden')
                })
            }
        }
        
        function initLine(myChart, settings){
            var theme = {
                color: [
                    '#FFD860','#9BCA63','#2c71b5'
                ]
            };
            var option = {
                title: {
                    text: '活跃统计图',
                    x: '40',
                    y: '10'
                },
                backgroundColor: '#ffffff',
                tooltip : {
                    trigger: 'axis',
                    formatter: function(params){
                            return '日期: ' + params[0].name + '<br/>' + params[0].seriesName + ': ' + params[0].value;
                    }
                },
                legend: {
                    data: settings.legendNames,
                    x: '150',
                    y: '15'
                },
                grid: {
                    x: 80,
                    height: '200'
                },
                dataZoom : {
                    show : true,
                    realtime : true,
                    y: 35,
                    height: 20,
                    start : 0,
                    end : 100
                },
                xAxis : [
                    {
                        type : 'category',
                        boundaryGap : false,
                        axisLine: {onZero: false},
                        data : settings.timeData,
                        name: '时间'
                    }
                ],
                yAxis : [
                    {
                        type : 'value'
                    }
                ],
                series : [
                    {
                        name:settings.legendNames[0],
                        type:'line',
                        smooth: true,
                        itemStyle: {normal: {areaStyle: {type: 'default'}}},
                        data:settings.valueDatas[0]
                    }, {
                        name:settings.legendNames[1],
                        type:'line',
                        smooth: true,
                        itemStyle: {normal: {areaStyle: {type: 'default'}}},
                        data:settings.valueDatas[1]
                    }, {
                        name:settings.legendNames[2],
                        type:'line',
                        smooth: true,
                        itemStyle: {normal: {areaStyle: {type: 'default'}}},
                        data:settings.valueDatas[2]
                    }
                ]
            };
            myChart.setOption(option).setTheme(theme);
            myChart.hideLoading();
        }
    }])
})(window, window.angular);